<template>
	<view class="reviews-container">
		<!-- 自定义导航栏 -->
		<view class="custom-navbar" :style="{ paddingTop: safeAreaInsetTop + 'px' }">
			<view class="navbar-content">
				<view class="navbar-left" @click="goBack">
					<text class="back-icon">‹</text>
				</view>
				<view class="navbar-center">
					<text class="navbar-title">商品评价</text>
				</view>
				<view class="navbar-right"></view>
			</view>
		</view>

		<!-- 主要内容区域 -->
		<scroll-view 
			class="main-content" 
			scroll-y="true"
			:refresher-enabled="true"
			:refresher-triggered="isRefreshing"
			@refresherrefresh="onRefresh"
			@scrolltolower="onLoadMore"
		>


			<!-- 筛选导航 -->
			<view class="filter-navigation">
				<view class="nav-header">
					<text class="nav-title">评价筛选</text>
					<text class="total-count">共{{ totalCount }}条评价</text>
				</view>
				<view class="filter-tabs">
					<view 
						v-for="(filter, index) in filterOptions" 
						:key="index"
						class="filter-tab"
						:class="{ 'active': currentFilter === filter.value }"
						@click="changeFilter(filter.value)"
					>
						<text class="tab-text">{{ filter.label }}</text>
					</view>
				</view>
			</view>

			<!-- 评价列表 -->
			<view class="review-list">
				<view 
					v-for="(review, index) in reviewList" 
					:key="index" 
					class="review-item"
				>
					<view class="review-header">
						<image 
							class="user-avatar" 
							:src="getUserAvatar(review)" 
						/>
						<view class="review-info">
							<text class="user-name">{{ getUserNickname(review) }}</text>
							<view class="review-rating">
								<text 
									v-for="star in 5" 
									:key="star" 
									class="star"
									:class="{ 'active': star <= (review.scoreStar || 5) }"
								>★</text>
							</view>
							<text class="review-spec" v-if="review.spec">{{ review.spec }}</text>
						</view>
						<text class="review-date">{{ formatDate(review.reviewTime) }}</text>
					</view>
					
					<text class="review-content">{{ review.content }}</text>
					
					<!-- 根据原型图，图片显示在内容下方，4列布局 -->
					<view v-if="review.reviewImages && review.reviewImages.length > 0" class="review-images-grid">
						<image 
							v-for="(img, imgIndex) in review.reviewImages" 
							:key="imgIndex"
							class="review-img-grid" 
							:src="getReviewImageUrl(img)" 
							mode="aspectFill"
							@click="previewReviewImages(getReviewImagesUrls(review.reviewImages), imgIndex)"
						/>
					</view>
					
					<!-- 商家回复 -->
					<view v-if="review.reply" class="merchant-reply">
						<view class="reply-header">
							<text class="reply-label">商家回复：</text>
						</view>
						<text class="reply-content">{{ review.reply }}</text>
					</view>
				</view>
			</view>

			<!-- 加载更多提示 -->
			<view v-if="hasMore" class="load-more">
				<text class="load-text">{{ isLoading ? '正在加载...' : '上拉加载更多' }}</text>
			</view>
			<view v-else-if="reviewList.length > 0" class="no-more">
				<text class="no-more-text">没有更多评价了</text>
			</view>

			<!-- 空状态 -->
			<view v-if="!isLoading && reviewList.length === 0" class="empty-state">
				<view class="empty-icon">📝</view>
				<text class="empty-text">暂无评价</text>
				<text class="empty-desc">快来成为第一个评价的用户吧</text>
			</view>

			<!-- 底部安全区域 -->
			<view class="bottom-safe-area" :style="{ height: safeAreaInsetBottom + 'px' }"></view>
		</scroll-view>

		<!-- 加载组件 -->
		<ob-loading :visible="isLoading && currentPage === 1" text="加载中..." />
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getPlatform, formatDate } from '../../utils/common.js'
import productApi from '../../api/product.js'
import { resolveAvatarUrl, resolveMediaUrl } from '../../utils/avatar.js'

// 获取系统信息
const platform = getPlatform()
const safeAreaInsetTop = platform.safeAreaInsetTop || 0
const safeAreaInsetBottom = platform.safeAreaInsetBottom || 0

// 响应式数据
const productId = ref('')
const reviewList = ref([])
const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const isLoading = ref(false)
const isRefreshing = ref(false)
const currentFilter = ref('all')

// 筛选选项
const filterOptions = [
	{ label: '全部', value: 'all' },
	{ label: '好评', value: 1 },
	{ label: '中评', value: 2 },
	{ label: '差评', value: 3 }
]

// 页面加载
onMounted(() => {
	const pages = getCurrentPages()
	const currentPage = pages[pages.length - 1]
	const options = currentPage.options
	
	productId.value = options.productId
	
	if (productId.value) {
		loadReviews()
	} else {
		uni.showToast({
			title: '商品信息获取失败',
			icon: 'none'
		})
	}
})

// 加载评价列表
const loadReviews = async (loadMore = false) => {
	if (isLoading.value) return
	
	try {
		isLoading.value = true
		
		if (!loadMore) {
			currentPage.value = 1
			reviewList.value = []
		}
		
		const params = {
			pageNum: currentPage.value,
			pageSize: pageSize.value
		}
		
		// 添加评分筛选参数
		if (currentFilter.value !== 'all') {
			params.sort = currentFilter.value
		}
		
		const response = await productApi.getProductEvaluation(productId.value, params)
		console.log('评价列表响应:', response)
		
		if (response) {
			// 处理分页数据
			let newReviews = []
			let total = 0
			
			if (Array.isArray(response)) {
				newReviews = response
				total = response.length
			} else if (response.list && Array.isArray(response.list)) {
				newReviews = response.list
				total = response.total || response.list.length
			} else if (response.records && Array.isArray(response.records)) {
				// 支持MyBatis Plus分页格式
				newReviews = response.records
				total = response.total || response.records.length
			}
			
			if (loadMore) {
				reviewList.value = [...reviewList.value, ...newReviews]
			} else {
				reviewList.value = newReviews
			}
			
			totalCount.value = total
			hasMore.value = newReviews.length === pageSize.value
		}
	} catch (error) {
		console.error('加载评价失败:', error)
		uni.showToast({
			title: '加载失败，请重试',
			icon: 'none'
		})
	} finally {
		isLoading.value = false
		isRefreshing.value = false
	}
}



// 切换筛选条件
const changeFilter = (filter) => {
	currentFilter.value = filter
	loadReviews()
}

// 下拉刷新
const onRefresh = () => {
	isRefreshing.value = true
	loadReviews()
}

// 加载更多
const onLoadMore = () => {
	if (hasMore.value && !isLoading.value) {
		currentPage.value++
		loadReviews(true)
	}
}

// 预览图片
const previewImages = (images, currentIndex) => {
	uni.previewImage({
		urls: images,
		current: currentIndex
	})
}

// 获取用户头像（不使用默认头像，按需解析为绝对URL）
const getUserAvatar = (review) => {
  const avatar = review?.user?.avatar || ''
  return resolveAvatarUrl(avatar)
}

// 获取用户昵称
const getUserNickname = (review) => {
	if (review.user && review.user.nickName) {
		return review.user.nickName
	}
	return '匿名用户'
}

// 获取评价图片URL（解析相对路径为绝对URL）
const getReviewImageUrl = (imageObj) => {
  if (!imageObj) return ''
  const imageUrl = imageObj.imageUrl || imageObj.url || imageObj
  return resolveMediaUrl(imageUrl)
}

// 获取评价图片URL数组
const getReviewImagesUrls = (images) => {
	if (!images || !Array.isArray(images)) return []
	return images.map(img => getReviewImageUrl(img)).filter(url => url)
}

// 预览评价图片
const previewReviewImages = (images, currentIndex) => {
	if (!images || images.length === 0) return
	uni.previewImage({
		urls: images,
		current: currentIndex || 0
	})
}

// 返回上一页
const goBack = () => {
	uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.reviews-container {
	min-height: 100vh;
	background: #FFFFFF;
}

.custom-navbar {
	background: #FFFFFF;
	border-bottom: 1px solid #F0F0F0;
	position: sticky;
	top: 0;
	z-index: 100;
}

.navbar-content {
	display: flex;
	align-items: center;
	justify-content: space-between;
	height: 44px;
	padding: 0 15px;
}

.navbar-left,
.navbar-right {
	width: 44px;
	height: 44px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.back-icon {
	font-size: 24px;
	color: #333333;
	font-weight: bold;
}

.navbar-center {
	flex: 1;
	text-align: center;
}

.navbar-title {
	font-size: 18px;
	font-weight: 500;
	color: #333333;
}

.main-content {
	flex: 1;
	height: calc(100vh - 44px);
	background: #FFFFFF;
}



// 筛选导航
.filter-navigation {
	background: #FFFFFF;
	padding: 20px;
	margin-bottom: 10px;
}

.nav-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 16px;
}

.nav-title {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
}

.total-count {
	font-size: 14px;
	color: #666666;
}

.filter-tabs {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.filter-tab {
	flex: 1;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 40px;
	border-bottom: 2px solid transparent;
	transition: all 0.3s ease;
	cursor: pointer;
	
	&.active {
		border-bottom-color: #4FACFE;
		
		.tab-text {
			color: #4FACFE;
			font-weight: 500;
		}
	}
}

.tab-text {
	font-size: 15px;
	color: #666666;
	transition: all 0.3s ease;
}

// 评价列表
.review-list {
	background: #FFFFFF;
	margin-bottom: 10px;
}

.review-item {
	padding: 20px;
	border-bottom: 1px solid #f0f0f0;
	
	&:last-child {
		border-bottom: none;
	}
}

.review-header {
	display: flex;
	align-items: flex-start;
	gap: 12px;
	margin-bottom: 12px;
}

.user-avatar {
	width: 40px;
	height: 40px;
	border-radius: 20px;
	flex-shrink: 0;
}

.review-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.user-name {
	font-size: 14px;
	color: #333333;
	font-weight: 500;
}

.review-rating {
	display: flex;
	gap: 2px;
	
	.star {
		font-size: 12px;
		color: #ddd;
		
		&.active {
			color: #ffb400;
		}
	}
}

.review-spec {
	font-size: 12px;
	color: #999999;
}

.review-date {
	font-size: 12px;
	color: #999999;
	flex-shrink: 0;
}

.review-content {
	font-size: 14px;
	color: #333333;
	line-height: 1.6;
	margin-bottom: 12px;
	text-align: justify;
}

// 根据原型图优化的图片网格布局（4列）
.review-images-grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 8px;
	margin-top: 12px;
}

.review-img-grid {
	width: 100%;
	height: 80px;
	border-radius: 8px;
	overflow: hidden;
	cursor: pointer;
	transition: transform 0.2s ease;
	
	&:hover {
		transform: scale(1.05);
	}
}

.review-images {
	display: flex;
	gap: 8px;
	flex-wrap: wrap;
	margin-bottom: 12px;
}

.review-img {
	width: 80px;
	height: 80px;
	border-radius: 6px;
	cursor: pointer;
	transition: transform 0.2s ease;
	
	&:hover {
		transform: scale(1.05);
	}
}

// 商家回复
.merchant-reply {
	background: #f8f9fa;
	border-left: 3px solid #4FACFE;
	padding: 12px;
	border-radius: 0 6px 6px 0;
}

.reply-header {
	margin-bottom: 8px;
}

.reply-label {
	font-size: 13px;
	color: #4FACFE;
	font-weight: 500;
}

.reply-content {
	font-size: 14px;
	color: #666666;
	line-height: 1.5;
}

// 加载状态
.load-more,
.no-more {
	padding: 20px;
	text-align: center;
}

.load-text,
.no-more-text {
	font-size: 14px;
	color: #999999;
}

// 空状态
.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 60px 20px;
	text-align: center;
}

.empty-icon {
	font-size: 64px;
	margin-bottom: 16px;
	opacity: 0.5;
}

.empty-text {
	font-size: 16px;
	color: #333333;
	margin-bottom: 8px;
}

.empty-desc {
	font-size: 14px;
	color: #999999;
}

.bottom-safe-area {
	background: transparent;
}
</style>